<?php

namespace SunAdmin\Task\jobs;


use SunAdmin\Service\SystemInfoService;
use SunAdmin\Service\Ws\FdUidBinding;
use SunAdmin\Service\Ws\SendMessage;
use think\swoole\websocket\Event;

/**
 * 系统指标推送任务
 * 负责推送CPU和内存使用率到所有ws客户端
 */
class SystemMetricsJob extends JobBaseAbstract
{
    protected function main()
    {
        $this->log('开始执行ws系统指标推送任务', 'info');
        // 获取系统指标
        $service = new SystemInfoService();
        $metrics = null;
        try {
            $metrics = $service->getSystemMetrics();
        } catch (\Throwable $e) {
            $this->log('获取系统指标失败: ' . $e->getMessage().$e->getTraceAsString(), 'error');
            return; // 获取指标失败则直接返回，不继续执行
        }
        $sendMessage =  new SendMessage('admin');
        $fdUidBing = new FdUidBinding('admin');
        $uidList = $fdUidBing->getAllOnlineUids();
        if (!empty($uidList)) {
            foreach ($uidList as $uid) {
                $sendMessage->toUidSendMsg($uid,new Event('system_metrics',[
                    'cpu_usage' => $metrics['cpu_usage'] ?? 'N/A',
                    'memory_usage' => $metrics['memory_usage'] ?? 'N/A'
                ]));
            }
            $this->log('websocket系统指标推送任务执行完成,fds:'.implode('-',$uidList), 'info');
        }
    }
} 